﻿using System.Collections.Generic;
using System.Windows.Forms;
using MessageHandler;

namespace Chatclient
{
	public partial class FormContacts : Form
	{
		private Controller controller;
		ErrorHandler errorHandler = new ErrorHandler();

		public FormContacts(Controller controller)
		{
			this.controller = controller;
			controller.MessageReceived += new Controller.MessageReceivedEventHandler(controller_MessageReceived);
			InitializeComponent();
		}

		void controller_MessageReceived(object sender, MessageReceivedEventArgs e)
		{
			switch (e.Message.messageType)
			{
				case MessageType.CONTACTADD:
					HandleNewContact(e.Message);
					break;
				case MessageType.CONTACTSEARCH:
					HandleContactSearch(e.Message);
					break;
				default:
					break;
			}
		}

		private void HandleNewContact(MessageHandler.Message message)
		{
			ContactAddMessageType type = (ContactAddMessageType)message.Item;
			if (type.fromUser.Equals(this.controller.UserInfo))
			{
				errorHandler.ShowInformation(new ChatException(type.toUser.username + " befindet sich jetzt in Ihrer Kontaktliste.", "Kontakt hinzugefügt"));
			}
		}

		private void HandleContactSearch(MessageHandler.Message message)
		{
			ContactSearchMessageType type = (ContactSearchMessageType)message.Item;
			if (type.searchResultList == null || type.searchResultList.Length == 0)
			{
				errorHandler.ShowError(new ChatException("Keine Suchergebnisse gefunden."));
			}
			else
			{
				AddContactsToUI(new List<UserInfo>(type.searchResultList));
			}
		}

		private delegate void AddContactsCallback(List<UserInfo> users);
		private void AddContactsToUI(List<UserInfo> users)
		{
			if (InvokeRequired)
			{
				this.Invoke(new AddContactsCallback(AddContactsToUI), users);
			}
			else
			{
				lstBxContacts.Items.AddRange(users.ToArray());
			}
		}

		private void btnSearch_Click(object sender, System.EventArgs e)
		{
			if (txtBxSearch.Text != string.Empty)
			{
				controller.SearchForContacts(txtBxSearch.Text);
			}
		}

		private void lstBxContacts_SelectedValueChanged(object sender, System.EventArgs e)
		{
			if (lstBxContacts.SelectedItem == null)
			{
				btnAdd.Enabled = false;
			}
			else
			{
				btnAdd.Enabled = true;
			}
		}

		private void btnAdd_Click(object sender, System.EventArgs e)
		{
			controller.AddContact((UserInfo)lstBxContacts.SelectedItem);
		}

		private void FormContacts_FormClosed(object sender, FormClosedEventArgs e)
		{
			controller.MessageReceived -= controller_MessageReceived;
		}
	}
}
